package com.luxsoft.siipap.migracion.parches;

import java.sql.Types;
import java.util.List;
import java.util.Map;

import com.luxsoft.siipap.service.ServiceLocator2;

public class ActualizaUltimoCosto {
	
	private static String tabla="CLAVE_FALTANTE_TEMP";
	
	public static void actualizarUltimoCosto(){
		String sql="select CLAVE from @TABLA ";
		sql=sql.replaceAll("@TABLA", tabla);
		List<String> claves=ServiceLocator2.getAnalisisJdbcTemplate().queryForList(sql,String.class);
		for(String s:claves){
			acutalizarUltimoCosto(s);
		}
	}
	
	public static void acutalizarUltimoCosto(String clave){
		String sql="select b.FECHA as FECHA,a.ARTCLAVE" +
				//",a.neto*b.tc as NETO " +
				",a.neto as NETO, b.tc as TC " +
				" from SW_ANALISISDET a join SW_ANALISIS b on(a.ANALISIS_ID=b.ANALISIS_ID) where a.ARTCLAVE=? order by b.fecha desc";
		List<Map<String, Object>> data=ServiceLocator2.getAnalisisJdbcTemplate().queryForList(sql,new Object[]{clave});
		if(!data.isEmpty()){
			Map<String, Object> row=data.get(0);
			Number costo=(Number)row.get("NETO");
			row=data.get(0);
			String updateSql="update @TABLA set " +
			"COSTO=? " +
			",FECHAU=?" +
			",TC=?" +
			"where CLAVE=? ";
			updateSql=updateSql.replaceAll("@TABLA", tabla);
			int res=ServiceLocator2.getAnalisisJdbcTemplate().update(
					updateSql
					,new Object[]{costo.doubleValue(),row.get("FECHA"),row.get("TC"),clave
							}
					,new int[]{Types.NUMERIC,Types.DATE,Types.NUMERIC,Types.VARCHAR}
					);
			System.out.println("Clave: "+clave+" U.Costo: "+row.get("NETO")+" Update: "+res);
		}
		
	}
	
	public static void main(String[] args) {
		actualizarUltimoCosto();
	}

}
